package main

import (
	"bufio"
	"fmt"
	"gopkg.in/yaml.v2"
	"log"
	"os"
	"time"
)

type Teacher struct {
	Sub     string `yaml:"Sub"`     //课程号
	TeaName string `yaml:"TeaName"` //老师名称
	TeaAge  int64  `yaml:"TeaAge"`
}
type Student struct {
	StuName string `yaml:"StuName"`
	StuAge  int    `yaml:"StuAge"`
}
type School struct {
	Teacher `yaml:"Teacher"`
	Student `yaml:"Student"`
	Other   []string `yaml:"Other"`
	NowTime string   `yaml:"NowTime"`
}

func main() {
	//start := profile.Start(profile.CPUProfile,profile.ProfilePath("."))
	//defer start.Stop()
	log.Println("start ")
	s := School{
		Teacher: Teacher{
			Sub:     "计算机",
			TeaAge:  32,
			TeaName: "张三",
		},
		Student: Student{
			StuName: "芮",
			StuAge:  24,
		},
		Other:   []string{"操场", "篮球场", "足球场"},
		NowTime: time.Now().Format("2006-01-02 15:04:05"),
	}
	//此处是将 数据解析为yaml格式（包含空格、回车之内的格式符号）
	out, err := yaml.Marshal(s)
	if err != nil {
		log.Println(err)
		panic(err)
	}
	fmt.Printf("%+v", string(out))
	log.Printf("%+v", s)
	//编码文件的时候，请使用过对结构体的数据 不然会出错的
	path := "./yamlLearn/yaml/rxl.yaml"
	_, err = os.Create(path)
	if os.IsNotExist(err) {
		os.Mkdir(path, 6666)
	}
	StructToYamlFile(s, path)
	log.Println("=====================================")
	YamlFileToStruct(path)
}
func YamlFileToStruct(path string) {
	file, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	d := yaml.NewDecoder(file)
	sc := new(School)
	err = d.Decode(&sc)
	if err != nil {
		panic(err)
	}
	log.Printf("%+v", sc)
}
func StructToYamlFile(s interface{}, path string) {
	file, err := os.Create(path)
	if err != nil {
		fmt.Println(err)
		panic(err)
	}
	defer file.Close()
	d := yaml.NewEncoder(file)
	defer d.Close()
	errE := d.Encode(s)
	if errE != nil {
		fmt.Println(err)
		panic(err)
	}
}

func objectToWriterYamlFile(filename string, data []byte) {

	file, e := os.Create(filename)
	if e != nil {
		fmt.Println(e)
		return
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	defer writer.Flush()
	writer.Write([]byte(data))
}
